#include <iostream>
#include "blockQueue.hpp"
#include "Task.hpp"
#include <pthread.h>
#include <unistd.h>
#include <ctime>
#include <cstring>
#include <semaphore.h>

using namespace std;

void* consume(void* args)
{
    block_queue<task>* pq = static_cast<block_queue<task>*>(args);
    while(true)
    {
        task t = pq->pop();
        t.run();
        cout << pthread_self() << "处理了一个数据：" << t.get_result() << endl;
        sleep(1);
    }
}

void* produce(void* args)
{
    size_t len = strlen(operaters);
    block_queue<task>* pq = static_cast<block_queue<task>*>(args);
    int i = 1;
    while(true)
    {
        int data1 = rand() % 10 + 1;
        int data2 = rand() % 10;
        char op = operaters[rand() % 4];
        task t(data1, data2, op);
        pq->push(t);
        cout << "产生了一个任务：" << t.get_task() << endl;
    }
}

int main()
{
    srand(time(nullptr) ^ getpid());
    // 创建两个线程，一个是"生产者"，一个是"消费者"
    // 改成多线程，有手就行
    pthread_t c[3], p[3];
    // 两个线程都需要看到同一个阻塞队列，所以需要在堆空间new一个新的队列
    block_queue<task>* bq = new block_queue<task>;
    for(int i = 0; i < 3; ++i)
    {
        pthread_create(c + i, nullptr, consume, static_cast<void*>(bq));
        pthread_create(p + i, nullptr, produce, static_cast<void*>(bq));
    }

    for(int i = 0; i < 3; ++i)
    {
        pthread_join(c[i], nullptr);
        pthread_join(p[i], nullptr);
    }
    return 0;
}